import { useEffect, useRef, useState, useCallback } from 'react'
import { fabric } from 'fabric'
import { useCanvasStore } from '../store/canvasStore'
import { useImageStore } from '../store/imageStore'
import { useWindowStore } from '../store/windowStore'
import './Canvas.css'

// 扩展 fabric.Image 类型定义
declare module 'fabric' {
  namespace fabric {
    interface Image {
      originalScaleX?: number
      originalScaleY?: number
      filePath?: string
    }
  }
}

const { ipcRenderer } = window.require('electron')

export default function Canvas() {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const fabricCanvasRef = useRef<fabric.Canvas | null>(null)
  const [scale, setScale] = useState(1)
  const [isDragging, setIsDragging] = useState(false)
  const [isPanning, setIsPanning] = useState(false)
  const lastPosRef = useRef({ x: 0, y: 0 })
  const [opacity, setOpacity] = useState(1)
  const [isClickThrough, setIsClickThrough] = useState(false)
  
  // 从 store 中获取状态和方法
  const { 
    addImage,
    setCanvas,
    canvas,
    selectedObjects,
    setSelectedObjects,
    saveCanvas,
    loadCanvas,
    newCanvas
  } = useCanvasStore()

  const { addImage: imageStoreAddImage } = useImageStore()

  const {
    opacity: windowOpacity,
    isClickThrough: windowIsClickThrough,
    increaseOpacity,
    decreaseOpacity,
    toggleClickThrough
  } = useWindowStore()

  // 处理画布缩放
  const handleZoom = useCallback((delta: number, point?: { x: number; y: number }) => {
    if (!canvas) return

    const zoomFactor = delta > 0 ? 0.9 : 1.1
    const newZoom = scale * zoomFactor  // 移除缩放限制
    
    // 获取鼠标在画布上的位置
    const pointer = point || {
      x: canvas.width! / 2,
      y: canvas.height! / 2
    }

    // 获取当前视口变换
    const vpt = canvas.viewportTransform || [1, 0, 0, 1, 0, 0]
    
    // 计算鼠标在画布坐标系中的位置
    const mouseX = (pointer.x - vpt[4]) / vpt[0]
    const mouseY = (pointer.y - vpt[5]) / vpt[3]

    // 计算新的缩放比例
    const zoom = newZoom / vpt[0]

    // 更新视口变换
    canvas.setViewportTransform([
      vpt[0] * zoom,
      vpt[1],
      vpt[2],
      vpt[3] * zoom,
      pointer.x - mouseX * vpt[0] * zoom,
      pointer.y - mouseY * vpt[3] * zoom
    ])

    setScale(newZoom)
  }, [canvas, scale])

  // 处理滚轮事件
  const handleWheel = useCallback((e: React.WheelEvent<HTMLDivElement>) => {
    e.preventDefault()
    if (!canvas) return

    // 获取鼠标在画布上的位置
    const rect = canvas.getElement().getBoundingClientRect()
    const pointer = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    }
    
    handleZoom(e.deltaY, pointer)
  }, [canvas, handleZoom])

  // 处理鼠标按下事件
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (!canvas) return

    // 如果按下空格键或中键，进入平移模式
    if (e.button === 1 || (e.button === 0 && e.altKey)) {
      setIsPanning(true)
      lastPosRef.current = { x: e.clientX, y: e.clientY }
      canvas.selection = false
      canvas.defaultCursor = 'grab'
      e.preventDefault()
    }
  }, [canvas])

  // 处理鼠标移动事件
  const handleMouseMove = useCallback((e: React.MouseEvent) => {
    if (!canvas || !isPanning) return

    const dx = e.clientX - lastPosRef.current.x
    const dy = e.clientY - lastPosRef.current.y

    // 平移画布
    canvas.relativePan({ x: dx, y: dy })
    lastPosRef.current = { x: e.clientX, y: e.clientY }
  }, [canvas, isPanning])

  // 处理鼠标松开事件
  const handleMouseUp = useCallback(() => {
    if (!canvas) return

    if (isPanning) {
      setIsPanning(false)
      canvas.selection = true
      canvas.defaultCursor = 'default'
    }
  }, [canvas, isPanning])

  // 初始化画布
  useEffect(() => {
    if (!canvasRef.current) return

    const fabricCanvas = new fabric.Canvas(canvasRef.current, {
      width: window.innerWidth,
      height: window.innerHeight,
      backgroundColor: '#1e1e1e',
      selection: true,
      preserveObjectStacking: true,
      // 设置画布属性
      stopContextMenu: true, // 禁用右键菜单
      fireRightClick: true,  // 启用右键事件
      renderOnAddRemove: true,
    })

    // 设置画布实例
    setCanvas(fabricCanvas)
    fabricCanvasRef.current = fabricCanvas

    // 设置画布视口变换
    fabricCanvas.setViewportTransform([1, 0, 0, 1, 0, 0])

    // 监听选中事件
    fabricCanvas.on('selection:created', (e) => {
      const selected = e.selected?.[0] as fabric.Image
      if (selected && selected.type === 'image') {
        // 保存当前缩放状态
        selected.originalScaleX = selected.scaleX
        selected.originalScaleY = selected.scaleY
        
        // 触发自定义事件，通知浮动工具栏
        const event = new CustomEvent('image-selected', {
          detail: {
            target: selected,
            pointer: fabricCanvas.getPointer(e.e),
          },
        })
        window.dispatchEvent(event)
      }
    })

    fabricCanvas.on('selection:updated', (e) => {
      const selected = e.selected?.[0] as fabric.Image
      if (selected && selected.type === 'image') {
        // 保存当前缩放状态
        selected.originalScaleX = selected.scaleX
        selected.originalScaleY = selected.scaleY
        
        const event = new CustomEvent('image-selected', {
          detail: {
            target: selected,
            pointer: fabricCanvas.getPointer(e.e),
          },
        })
        window.dispatchEvent(event)
      }
    })

    fabricCanvas.on('selection:cleared', () => {
      // 触发自定义事件，通知浮动工具栏隐藏
      const event = new CustomEvent('image-deselected')
      window.dispatchEvent(event)
    })

    // 监听对象修改事件
    fabricCanvas.on('object:modified', (e) => {
      const target = e.target as fabric.Image
      if (target && target.type === 'image') {
        // 保存修改后的缩放状态
        target.originalScaleX = target.scaleX
        target.originalScaleY = target.scaleY
      }
    })

    // 监听画布点击事件
    fabricCanvas.on('mouse:down', (e) => {
      if (!e.target) {
        // 点击空白处时触发取消选中事件
        const event = new CustomEvent('canvas-clicked', {
          detail: {
            pointer: fabricCanvas.getPointer(e.e),
          },
        })
        window.dispatchEvent(event)
      }
    })

    // 监听窗口大小变化
    const handleResize = () => {
      fabricCanvas.setWidth(window.innerWidth)
      fabricCanvas.setHeight(window.innerHeight)
      fabricCanvas.renderAll()
    }

    window.addEventListener('resize', handleResize)

    // 清理函数
    return () => {
      window.removeEventListener('resize', handleResize)
      fabricCanvas.dispose()
    }
  }, [setCanvas])

  // 处理图片导入
  useEffect(() => {
    const handleImportImages = async () => {
      const filePaths = await ipcRenderer.invoke('open-file-dialog')
      if (!filePaths || !filePaths.length) return

      for (const filePath of filePaths) {
        fabric.Image.fromURL(`file://${filePath}`, (img) => {
          // 保存文件路径
          img.filePath = filePath

          // 调整图片大小以适应画布
          const maxWidth = canvas?.width ? canvas.width * 0.8 : 800
          const maxHeight = canvas?.height ? canvas.height * 0.8 : 600
          
          const scale = Math.min(
            maxWidth / img.width!,
            maxHeight / img.height!
          )

          img.scale(scale)
          
          // 随机位置
          const x = Math.random() * (canvas?.width! - img.width! * scale) / 2
          const y = Math.random() * (canvas?.height! - img.height! * scale) / 2
          
          img.set({
            left: x,
            top: y,
            selectable: true,
            hasControls: true,
            hasBorders: true,
            lockRotation: false,
            lockScalingX: false,
            lockScalingY: false,
          })

          canvas?.add(img)
          canvas?.renderAll()
          imageStoreAddImage(img)
        })
      }
    }

    // 监听导入图片事件
    ipcRenderer.on('import-images', handleImportImages)

    return () => {
      ipcRenderer.removeListener('import-images', handleImportImages)
    }
  }, [canvas, imageStoreAddImage])

  // 处理拖拽导入
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    
    // 检查是否包含文件
    if (e.dataTransfer.types.includes('Files')) {
      setIsDragging(true)
      e.dataTransfer.dropEffect = 'copy'
    }
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    
    // 确保鼠标真的离开了画布区域
    const rect = e.currentTarget.getBoundingClientRect()
    const x = e.clientX
    const y = e.clientY
    
    if (
      x <= rect.left ||
      x >= rect.right ||
      y <= rect.top ||
      y >= rect.bottom
    ) {
      setIsDragging(false)
    }
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    
    // 设置拖拽效果为复制
    if (e.dataTransfer.types.includes('Files')) {
      e.dataTransfer.dropEffect = 'copy'
    }
  }

  // 修改加载图片函数
  const loadImage = (file: File, x: number, y: number, scale: number) => {
    const reader = new FileReader()
    reader.onload = (event) => {
      fabric.Image.fromURL(event.target?.result as string, (img) => {
        // 保存文件路径（如果是拖拽的文件）
        if (file.path) {
          img.filePath = file.path
        }

        // 计算图片在画布坐标系中的位置
        const canvasTransform = canvas?.viewportTransform || [1, 0, 0, 1, 0, 0]
        const zoom = canvasTransform[0]
        const panX = canvasTransform[4]
        const panY = canvasTransform[5]

        // 调整图片位置以考虑画布的缩放和平移
        const adjustedX = (x - panX) / zoom
        const adjustedY = (y - panY) / zoom
        const adjustedScale = scale / zoom

        img.scale(adjustedScale)
        
        // 设置图片属性
        Object.assign(img, {
          left: adjustedX,
          top: adjustedY,
          selectable: true,
          hasControls: true,
          hasBorders: true,
          lockRotation: false,
          lockScalingX: false,
          lockScalingY: false,
          cornerColor: '#00a8ff',
          cornerSize: 10,
          transparentCorners: false,
          borderColor: '#00a8ff',
          borderScaleFactor: 2,
          minScaleLimit: 0.1,
          originalScaleX: adjustedScale,
          originalScaleY: adjustedScale,
        })

        // 添加图片加载动画
        img.set({
          opacity: 0,
          scaleX: adjustedScale * 0.8,
          scaleY: adjustedScale * 0.8,
        })

        canvas?.add(img)
        canvas?.renderAll()
        imageStoreAddImage(img)

        // 执行加载动画
        fabric.util.animate({
          startValue: 0,
          endValue: 1,
          duration: 300,
          onChange: (value) => {
            img.set({
              opacity: value,
              scaleX: adjustedScale * (0.8 + value * 0.2),
              scaleY: adjustedScale * (0.8 + value * 0.2),
            })
            canvas?.renderAll()
          },
          onComplete: () => {
            img.set({
              opacity: 1,
              scaleX: adjustedScale,
              scaleY: adjustedScale,
            })
            img.originalScaleX = adjustedScale
            img.originalScaleY = adjustedScale
            canvas?.renderAll()
          },
        })
      })
    }
    reader.readAsDataURL(file)
  }

  // 添加图片事件监听
  useEffect(() => {
    if (!canvas) return

    const handleImageMouseDown = (e: fabric.IEvent) => {
      const target = e.target
      if (!target || target.type !== 'image') return

      const mouseEvent = e.e as MouseEvent
      if (mouseEvent.altKey) {
        // Alt + 点击：复制图片
        const clone = fabric.util.object.clone(target)
        clone.set({
          left: target.left! + 20,
          top: target.top! + 20,
        })
        canvas.add(clone)
        canvas.renderAll()
        imageStoreAddImage(clone as fabric.Image)
      }
    }

    canvas.on('mouse:down', handleImageMouseDown)

    return () => {
      canvas.off('mouse:down', handleImageMouseDown)
    }
  }, [canvas, imageStoreAddImage])

  // 计算最佳网格布局的辅助函数
  const calculateOptimalGrid = (images: { width: number; height: number }[], areaWidth: number, areaHeight: number, padding: number) => {
    const totalImages = images.length
    if (totalImages === 0) return { cols: 0, rows: 0, cellWidth: 0, cellHeight: 0 }

    // 计算所有图片的平均宽高比
    const avgAspectRatio = images.reduce((sum, img) => sum + (img.width / img.height), 0) / totalImages

    // 根据区域宽高比和图片平均宽高比计算最佳列数
    const areaAspectRatio = areaWidth / areaHeight
    const optimalCols = Math.ceil(Math.sqrt(totalImages * areaAspectRatio / avgAspectRatio))
    const optimalRows = Math.ceil(totalImages / optimalCols)

    // 计算每个单元格的尺寸
    const cellWidth = (areaWidth - padding * (optimalCols + 1)) / optimalCols
    const cellHeight = (areaHeight - padding * (optimalRows + 1)) / optimalRows

    return {
      cols: optimalCols,
      rows: optimalRows,
      cellWidth,
      cellHeight
    }
  }

  // 计算图片在网格中的实际尺寸
  const calculateImageSize = (img: { width: number; height: number }, cellWidth: number, cellHeight: number) => {
    const scale = Math.min(
      cellWidth / img.width,
      cellHeight / img.height
    )
    return {
      width: img.width * scale,
      height: img.height * scale,
      scale
    }
  }

  // 检查位置是否可用的辅助函数（增加边距检查）
  const isPositionAvailable = (x: number, y: number, width: number, height: number, occupiedAreas: any[], padding: number) => {
    const newArea = {
      left: x - padding,
      top: y - padding,
      right: x + width + padding,
      bottom: y + height + padding
    }

    return !occupiedAreas.some(area => 
      !(newArea.right < area.left || 
        newArea.left > area.right || 
        newArea.bottom < area.top || 
        newArea.top > area.bottom)
    )
  }

  // 获取已占用区域的辅助函数
  const getOccupiedAreas = () => {
    if (!canvas) return []
    
    return canvas.getObjects().map(obj => {
      const rect = obj.getBoundingRect()
      return {
        left: rect.left,
        top: rect.top,
        right: rect.left + rect.width * obj.scaleX!,
        bottom: rect.top + rect.height * obj.scaleY!,
        width: rect.width * obj.scaleX!,
        height: rect.height * obj.scaleY!
      }
    })
  }

  // 计算可用区域的辅助函数
  const calculateAvailableArea = (occupiedAreas: any[], canvasWidth: number, canvasHeight: number, padding: number) => {
    // 如果没有已占用的区域，返回整个画布
    if (occupiedAreas.length === 0) {
      return {
        left: padding,
        top: padding,
        right: canvasWidth - padding,
        bottom: canvasHeight - padding,
        width: canvasWidth - padding * 2,
        height: canvasHeight - padding * 2
      }
    }

    // 找到最右边的已占用区域
    const rightmostArea = occupiedAreas.reduce((max, area) => 
      area.right > max.right ? area : max
    , occupiedAreas[0])

    // 如果最右边的区域靠近画布右边缘，从顶部开始新的一行
    if (rightmostArea.right > canvasWidth * 0.7) {
      // 找到最底部的已占用区域
      const bottommostArea = occupiedAreas.reduce((max, area) => 
        area.bottom > max.bottom ? area : max
      , occupiedAreas[0])

      return {
        left: padding,
        top: bottommostArea.bottom + padding,
        right: canvasWidth - padding,
        bottom: canvasHeight - padding,
        width: canvasWidth - padding * 2,
        height: canvasHeight - bottommostArea.bottom - padding * 2
      }
    }

    // 否则，从最右边区域的右侧开始
    return {
      left: rightmostArea.right + padding,
      top: padding,
      right: canvasWidth - padding,
      bottom: canvasHeight - padding,
      width: canvasWidth - rightmostArea.right - padding * 2,
      height: canvasHeight - padding * 2
    }
  }

  // 修改拖拽处理函数
  const handleDrop = async (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)

    try {
      const files = Array.from(e.dataTransfer.files)
      const imageFiles = files.filter(file => file.type.startsWith('image/'))
      
      if (imageFiles.length === 0) return

      // 获取鼠标位置
      const rect = e.currentTarget.getBoundingClientRect()
      const mouseX = e.clientX - rect.left
      const mouseY = e.clientY - rect.top

      // 定义矩形区域的大小
      const areaWidth = 800  // 矩形区域宽度
      const areaHeight = 600 // 矩形区域高度
      const padding = 30     // 图片间距

      // 获取已占用的区域
      const occupiedAreas = getOccupiedAreas()
      const canvasWidth = canvas?.width || window.innerWidth
      const canvasHeight = canvas?.height || window.innerHeight

      // 计算可用区域
      const availableArea = calculateAvailableArea(occupiedAreas, canvasWidth, canvasHeight, padding)

      // 计算矩形区域的左上角坐标
      const areaLeft = mouseX >= availableArea.left && mouseX <= availableArea.right
        ? mouseX - areaWidth / 2
        : availableArea.left
      const areaTop = mouseY >= availableArea.top && mouseY <= availableArea.bottom
        ? mouseY - areaHeight / 2
        : availableArea.top

      // 确保区域不会超出可用空间
      const finalAreaLeft = Math.max(availableArea.left, Math.min(areaLeft, availableArea.right - areaWidth))
      const finalAreaTop = Math.max(availableArea.top, Math.min(areaTop, availableArea.bottom - areaHeight))

      // 预先获取所有图片的尺寸
      const imageSizes = await Promise.all(
        imageFiles.map(file => getImageSize(file))
      )

      // 计算最佳网格布局
      let { cols, rows, cellWidth, cellHeight } = calculateOptimalGrid(
        imageSizes,
        areaWidth,
        areaHeight,
        padding
      )

      // 计算所有图片的总面积
      let totalArea = 0
      for (let i = 0; i < imageSizes.length; i++) {
        const { width, height } = calculateImageSize(imageSizes[i], cellWidth, cellHeight)
        totalArea += width * height
      }
      const availableAreaSize = (cellWidth + padding) * cols * (cellHeight + padding) * rows
      // 如果总面积大于可用区域，统一缩小所有图片
      let globalScale = 1
      if (totalArea > areaWidth * areaHeight) {
        globalScale = Math.sqrt((areaWidth * areaHeight) / totalArea) * 0.95 // 预留一点间距
      }

      // 加载并排列图片
      for (let i = 0; i < imageFiles.length; i++) {
        const file = imageFiles[i]
        const row = Math.floor(i / cols)
        const col = i % cols
        const imgSize = imageSizes[i]

        // 计算图片在网格中的实际尺寸
        let { width, height, scale } = calculateImageSize(imgSize, cellWidth, cellHeight)
        width *= globalScale
        height *= globalScale
        scale *= globalScale

        // 计算图片在矩形区域内的位置
        let x = finalAreaLeft + padding + col * (cellWidth + padding) + (cellWidth - width) / 2
        let y = finalAreaTop + padding + row * (cellHeight + padding) + (cellHeight - height) / 2

        // 确保图片不会超出画布边界
        x = Math.max(padding, Math.min(x, canvasWidth - width - padding))
        y = Math.max(padding, Math.min(y, canvasHeight - height - padding))

        // 如果位置被占用，寻找最近的可用位置
        if (!isPositionAvailable(x, y, width, height, occupiedAreas, padding)) {
          const searchRadius = Math.max(cellWidth, cellHeight)
          let found = false
          let searchAngle = 0
          while (!found && searchAngle < 360) {
            for (let r = 0; r < searchRadius && !found; r += padding) {
              const testX = x + r * Math.cos(searchAngle * Math.PI / 180)
              const testY = y + r * Math.sin(searchAngle * Math.PI / 180)
              if (testX >= padding && 
                  testX <= canvasWidth - width - padding &&
                  testY >= padding && 
                  testY <= canvasHeight - height - padding &&
                  isPositionAvailable(testX, testY, width, height, occupiedAreas, padding)) {
                x = testX
                y = testY
                found = true
                break
              }
            }
            searchAngle += 45
          }
        }

        // 加载图片
        loadImage(file, x, y, scale)
        // 更新已占用区域
        occupiedAreas.push({
          left: x,
          top: y,
          right: x + width,
          bottom: y + height,
          width,
          height
        })
      }
    } catch (error) {
      console.error('Error handling drop:', error)
    }
  }

  // 修改粘贴处理函数
  const handlePaste = async (e: ClipboardEvent) => {
    e.preventDefault()
    
    const items = e.clipboardData?.items
    if (!items) return

    const imageFiles: File[] = []
    
    for (let i = 0; i < items.length; i++) {
      const item = items[i]
      if (item.type.startsWith('image/')) {
        const file = item.getAsFile()
        if (file) {
          imageFiles.push(file)
        }
      }
    }

    if (imageFiles.length === 0) return

    // 获取已占用的区域
    const occupiedAreas = getOccupiedAreas()
    const canvasWidth = canvas?.width || window.innerWidth
    const canvasHeight = canvas?.height || window.innerHeight
    const padding = 30

    // 计算可用区域
    const availableArea = calculateAvailableArea(occupiedAreas, canvasWidth, canvasHeight, padding)

    // 定义矩形区域的大小
    const areaWidth = 800
    const areaHeight = 600

    // 从可用区域的左上角开始排列
    const areaLeft = availableArea.left
    const areaTop = availableArea.top

    // 预先获取所有图片的尺寸
    const imageSizes = await Promise.all(
      imageFiles.map(file => getImageSize(file))
    )

    // 计算最佳网格布局
    const { cols, rows, cellWidth, cellHeight } = calculateOptimalGrid(
      imageSizes,
      areaWidth,
      areaHeight,
      padding
    )

    // 加载并排列图片
    for (let i = 0; i < imageFiles.length; i++) {
      const file = imageFiles[i]
      const row = Math.floor(i / cols)
      const col = i % cols
      const imgSize = imageSizes[i]

      // 计算图片在网格中的实际尺寸
      const { width, height, scale } = calculateImageSize(imgSize, cellWidth, cellHeight)

      // 计算图片在矩形区域内的位置
      let x = areaLeft + padding + col * (cellWidth + padding) + (cellWidth - width) / 2
      let y = areaTop + padding + row * (cellHeight + padding) + (cellHeight - height) / 2

      // 确保图片不会超出画布边界
      x = Math.max(padding, Math.min(x, canvasWidth - width - padding))
      y = Math.max(padding, Math.min(y, canvasHeight - height - padding))

      // 如果位置被占用，寻找最近的可用位置
      if (!isPositionAvailable(x, y, width, height, occupiedAreas, padding)) {
        // 在矩形区域周围搜索可用位置
        const searchRadius = Math.max(cellWidth, cellHeight)
        let found = false
        let searchAngle = 0
        
        while (!found && searchAngle < 360) {
          for (let r = 0; r < searchRadius && !found; r += padding) {
            const testX = x + r * Math.cos(searchAngle * Math.PI / 180)
            const testY = y + r * Math.sin(searchAngle * Math.PI / 180)
            
            if (testX >= padding && 
                testX <= canvasWidth - width - padding &&
                testY >= padding && 
                testY <= canvasHeight - height - padding &&
                isPositionAvailable(testX, testY, width, height, occupiedAreas, padding)) {
              x = testX
              y = testY
              found = true
              break
            }
          }
          searchAngle += 45
        }
      }

      // 加载图片
      loadImage(file, x, y, scale)
      
      // 更新已占用区域
      occupiedAreas.push({
        left: x,
        top: y,
        right: x + width,
        bottom: y + height,
        width,
        height
      })
    }
  }

  // 获取图片尺寸的辅助函数
  const getImageSize = (file: File): Promise<{ width: number; height: number }> => {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = () => {
        const size = {
          width: img.width,
          height: img.height,
        }
        URL.revokeObjectURL(img.src) // 清理 URL
        resolve(size)
      }
      img.onerror = (error) => {
        URL.revokeObjectURL(img.src) // 清理 URL
        reject(error)
      }
      img.src = URL.createObjectURL(file)
    })
  }

  // 添加复制事件处理
  const handleCopy = (e: ClipboardEvent) => {
    if (!canvas || !selectedObjects.length) return

    e.preventDefault()
    
    // 将选中的图片转换为 base64
    const selectedImages = selectedObjects.filter(obj => obj.type === 'image')
    if (selectedImages.length === 0) return

    // 创建一个临时的 canvas 来合并选中的图片
    const tempCanvas = document.createElement('canvas')
    const tempCtx = tempCanvas.getContext('2d')
    if (!tempCtx) return

    // 计算合并后图片的尺寸
    let maxWidth = 0
    let maxHeight = 0
    selectedImages.forEach((img: any) => {
      maxWidth = Math.max(maxWidth, img.width! * img.scaleX!)
      maxHeight = Math.max(maxHeight, img.height! * img.scaleY!)
    })

    tempCanvas.width = maxWidth
    tempCanvas.height = maxHeight

    // 将选中的图片绘制到临时 canvas
    selectedImages.forEach((img: any) => {
      const dataUrl = img.toDataURL()
      const imgElement = new Image()
      imgElement.src = dataUrl
      tempCtx.drawImage(imgElement, 0, 0)
    })

    // 将合并后的图片复制到剪贴板
    tempCanvas.toBlob((blob) => {
      if (blob) {
        const item = new ClipboardItem({ 'image/png': blob })
        e.clipboardData?.setData('image/png', tempCanvas.toDataURL('image/png'))
      }
    }, 'image/png')
  }

  useEffect(() => {
    // 添加粘贴事件监听
    const handlePasteEvent = (e: ClipboardEvent) => handlePaste(e)
    const handleCopyEvent = (e: ClipboardEvent) => handleCopy(e)
    
    window.addEventListener('paste', handlePasteEvent)
    window.addEventListener('copy', handleCopyEvent)

    return () => {
      window.removeEventListener('paste', handlePasteEvent)
      window.removeEventListener('copy', handleCopyEvent)
    }
  }, [canvas, selectedObjects])

  // 添加键盘事件监听
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // F8: 切换点击穿透
      if (e.key === 'F8') {
        e.preventDefault()
        toggleClickThrough()
      }
      // F6: 降低透明度
      else if (e.key === 'F6') {
        e.preventDefault()
        decreaseOpacity()
      }
      // F7: 提高透明度
      else if (e.key === 'F7') {
        e.preventDefault()
        increaseOpacity()
      }
      // Ctrl+N: 新建画布
      else if (e.key === 'n' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        const { canvas, newCanvas } = useCanvasStore.getState()
        if (canvas && canvas.getObjects().length > 0) {
          const confirmed = window.confirm('当前画布有未保存的内容，是否确定要新建画布？')
          if (!confirmed) return
        }
        newCanvas()
      }
      // Ctrl+S: 保存画布
      else if (e.key === 's' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        saveCanvas()
      }
      // Ctrl+O: 打开画布
      else if (e.key === 'o' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        loadCanvas()
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => {
      window.removeEventListener('keydown', handleKeyDown)
    }
  }, [toggleClickThrough, increaseOpacity, decreaseOpacity, saveCanvas, loadCanvas])

  return (
    <div 
      className={`canvas-wrapper ${isDragging ? 'drag-over' : ''} ${isPanning ? 'panning' : ''}`}
      onWheel={handleWheel}
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      onMouseLeave={handleMouseUp}
      onDrop={handleDrop}
      onDragOver={handleDragOver}
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
    >
      <canvas ref={canvasRef} />
      <div className="drop-zone">
        <div className="drop-zone-text">拖拽图片到这里</div>
      </div>
    </div>
  )
}